package com.xiaozhi.iot.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.tio.server.TioServerConfig;
import org.tio.websocket.server.WsServerStarter;

/**
 * @author weirdor
 */
@Configuration
@EnableConfigurationProperties(XiaoZhiWsProperties.class)
public class TioWsServerConfig {
    private static final Logger log = LoggerFactory.getLogger(TioWsServerConfig.class);

    private final XiaoZhiWsProperties props;
    private WsServerStarter starter;

    public TioWsServerConfig(XiaoZhiWsProperties props) {
        this.props = props;
    }

    @Bean
    public XiaoZhiWsMsgHandler chatWsMsgHandler() {
        return new XiaoZhiWsMsgHandler();
    }

    @Bean
    public WsServerStarter wsServerStarter(XiaoZhiWsMsgHandler handler) throws Exception {
        this.starter = new WsServerStarter(props.getPort(), handler);
        TioServerConfig cfg = starter.getTioServerConfig();
        cfg.setName(props.getName());
        cfg.setHeartbeatTimeout(props.getHeartbeatTimeout());
        return starter;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void startWs() throws Exception {
        if (starter != null) {
            starter.start(); // 启动 WS 服务
            log.info("t-io WebSocket listening on ws://0.0.0.0:{}", props.getPort());
        }
    }
}